package cl.regalloc.parse;

import java.util.HashMap;
import java.util.List;

public class BasicBlockFactory {

	private static HashMap<Label, BasicBlock> labeledBasicBlocks = new HashMap<Label, BasicBlock>(); 

	public static BasicBlock getBasicBlockWithLabel(Label labelName) {
		if (labeledBasicBlocks.containsKey(labelName))
			return labeledBasicBlocks.get(labelName);
		else {
			BasicBlock newBasicBlock = new BasicBlock();
			newBasicBlock.setLabel(labelName);
			labeledBasicBlocks.put(labelName, newBasicBlock);
			return labeledBasicBlocks.get(labelName);
		}
	}

	public static BasicBlock transferLinks(BasicBlock fromBlock, BasicBlock toBlock) {
		List<BasicBlock> prdcs = fromBlock.getPrdcs();
		List<BasicBlock> succs = fromBlock.getSuccs();

		for (BasicBlock currPrdc : prdcs) {
			toBlock.addPrdc(currPrdc);	/* transfer predecessors */
			currPrdc.addSucc(toBlock);	/* add itself to predecessor's succs */
			currPrdc.removeSucc(fromBlock);	/* remove old block from predecesor's succs */
		}

		for (BasicBlock currSucc : succs) {
			toBlock.addSucc(currSucc);	/* transfer successor */
			currSucc.addPrdc(toBlock);	/* add itself to successor's prdcs */
			currSucc.removePrdc(fromBlock);	/* remove old block from successor's prdcs */
		}

		fromBlock.clearAllPrdcs();	/* clear all predecessors of old block */
		fromBlock.clearAllSuccs();	/* clear all successors of old block */

		return toBlock;
	}

}
